var express = require('express');
const userModel = require('../database/models/userModel');
var router = express.Router();
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10); //盐，盐值越大密码强度越高，约耗费运算资源
var jwt = require('jsonwebtoken');
const { checkToken } = require('../utils/tools');
var secret = 'sdfajlsdkjflaskjdflasjdl12jlkjlasdkjf$asdfljl' //token签发的私钥

//注册接口
router.post('/',async (req,res)=>{
  let {username,password,roleId} = req.body
  //判断账号是否可用
  let result = await userModel.find({username})
  if(result.length){
    res.send({code:0,msg:'账号已被占用'})
    return
  }
  //密码加密
  var hash = bcrypt.hashSync(password, salt);
  //录入数据库
  await new userModel({username,"password":hash,roleId}).save()
  res.send({code:1,msg:'注册成功'})
})


// 登录接口
router.get('/', async function(req, res, next) {
  let {username,password} = req.query
  let result = await userModel.find({username})
  // 账号是否存在
  if(result.length==0){
    res.send({code:0,msg:'账号不存在，请注册'})
    return
  }
  // 验证密码正确性
  let hash = result[0].password  //加密密码
  let bool = bcrypt.compareSync(password,hash)
  if(!bool){
    res.send({code:0,msg:'密码错误，请重试'})
    return
  }
  // 签发token令牌（签发时间、有效时长）
  let token = jwt.sign({
    time:Date.now(),   //时间戳
    // expire:1000*60*60*24*7
    expire:1000*60*60*2  //有效时长
  },secret)
  let data = result[0]
  data.password = '' 
  res.send({code:1,msg:'登录成功',data,token})
});

//token认证接口
router.get('/auth',async (req,res)=>{
  console.log(req.headers);  //提取本次请求headers中携带的数据
  let {token} = req.headers
  //合法性判断
  try {
    let decoded = jwt.verify(token,secret)  //解析出token中携带的信息
    let {time,expire} = decoded
    // 有效性判断
    let now = Date.now()  //当前时间
    if(now-time>expire){
      res.send({code:402,msg:'token过期，请重新登录'})
      return
    }
  } catch (error) {
    res.send({code:401,msg:'非法token'})
    return
  }

  //合法且有效的token
  res.send({code:1,msg:'token验证通过'})
})

//用户信息更新（头像上传）
router.put('/',(req,res,next)=>{checkToken(req,res,next)},async(req,res)=>{
  // 用户id、更新的数据包
  let {id} = req.query
  try {
    let result = await userModel.updateOne({_id:id},req.body)
    res.send({code:1,msg:'用户信息更新成功'})
  } catch (error) {
    res.send({code:1,msg:'更新失败'})
  }
})

module.exports = router;
